//
//  ST_DetectFaceBeforeController.swift
//  btvideo
//
//  Created by mac on 2020/9/2.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwiftyAttributes
import MBProgressHUD
#if !targetEnvironment(simulator)
import IDLFaceSDK
#endif

class ST_DetectFaceBeforeController: ST_BTLightBarViewController {

    deinit {
        #if !targetEnvironment(simulator)
        FaceSDKManager.sharedInstance().uninitCollect()
        #endif
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        title_nav_btn.setTitleForAllStates("认证中心")
        
        
        view.addSubview(faceTitleLabel)
        faceTitleLabel.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.height.equalTo(25)
            make.top.equalTo(own_navigation_bar.snp.bottom).offset(10)
        }
        
        view.addSubview(faceContentLabel)
        faceContentLabel.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.height.equalTo(20)
            make.top.equalTo(faceTitleLabel.snp.bottom).offset(10)
        }
        
        
                
        var lastVerticalView:ST_AICenterFaceStatusCellChildBox?
        
        for (idx,item) in ST_AICenterFaceStatusCellChildBoxModel.setup_data().enumerated(){
            
            let rowIndex = idx % 2
            
            let itemView = ST_AICenterFaceStatusCellChildBox()
            
//            itemView.backgroundColor = .random
            
            itemView.model = item
            view.addSubview(itemView)
            
            if rowIndex == 0{
                itemView.snp.makeConstraints { (make) in
                    make.size.equalTo(ST_AICenterFaceStatusCellChildBox.size)
                    make.right.equalTo(view.snp.centerX).offset(-7)
                    
                    if let last = lastVerticalView{
                        make.top.equalTo(last.snp.bottom).offset(15)
                    }else{
                        make.top.equalTo(faceContentLabel.snp.bottom).offset(15)
                    }
                }
            }else{
                
                itemView.snp.makeConstraints { (make) in
                    make.size.equalTo(ST_AICenterFaceStatusCellChildBox.size)
                    make.left.equalTo(view.snp.centerX).offset(8)
                    if let last = lastVerticalView{
                        make.top.equalTo(last)
                    }else{
                        make.top.equalTo(faceContentLabel.snp.bottom).offset(15)
                    }
                }
            }
            if rowIndex == 0{
                lastVerticalView = itemView
            }
        }
        
        
        guard let lastView = lastVerticalView else {
            return
        }
        
        view.addSubview(baiduBox)
        baiduBox.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.right.equalToSuperview().offset(-15)
            if iPhoneXSeries{
                make.top.equalTo(lastView.snp.bottom).offset(33)
            }else{
                make.top.equalTo(lastView.snp.bottom).offset(10)
            }
            make.height.equalTo(180)
        }
        
        
        view.addSubview(lockImageView)
        
        lockImageView.snp.makeConstraints { (make) in
            make.centerX.equalTo(baiduBox)
            make.centerY.equalTo(baiduBox.snp.top)
        }
        
        baiduBox.addSubview(baiduTitleLabel)
        baiduTitleLabel.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(28)
        }
        
        baiduBox.addSubview(baiduContentLabel)
        baiduContentLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
            make.top.equalToSuperview().offset(60)
        }
        
        baiduBox.addSubview(sign_image_view)
        sign_image_view.snp.makeConstraints { (make) in
            make.width.equalTo(220)
            make.height.equalTo(22)
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-10)
        }
        
        
        view.addSubview(start_btn)
        start_btn.snp.makeConstraints { (make) in
            make.width.equalTo(260)
            make.height.equalTo(44)
            make.centerX.equalToSuperview()
            if iPhoneXSeries{
                make.bottom.equalToSuperview().offset(-BTSafeAreaBottom)
            }else{
                make.bottom.equalToSuperview().offset(-20)
            }
        }
        
        baiduConfig()
        
    }
    
    
    @objc func startHandle(){
        
        switch AVCaptureDevice.authorizationStatus(for: .video) {
            case .authorized: // The user has previously granted access to the camera.
                main_thread_execute {
                    self.next_step_action()
                }
            case .notDetermined: // The user has not yet been asked for camera access.
                AVCaptureDevice.requestAccess(for: .video) { granted in
                    
                    main_thread_execute {
                     
                        if granted {
                            self.next_step_action()
                        }else{
                            self.authorization_tips_handle()
                        }
                    }
                }
            default:
                main_thread_execute {
                    self.authorization_tips_handle()
                }
                break
        }
        
    }
    
    
    fileprivate func authorization_tips_handle(){
        
        
        let titleStr = "需要开启摄像头权限".withAttributes([Attribute.textColor(Color.init(red: 51, green: 51, blue: 51)!),Attribute.font(Font.systemFont(ofSize: 18, weight: UIFont.Weight.medium))])
        

        let style = NSMutableParagraphStyle()
        style.alignment = .center
        style.lineSpacing = 5

        let content_string = "真人认证需要访问你的摄像头\n立即前往开启？".withAttributes([Attribute.textColor(Color.init(red: 97, green: 102, blue: 111)!),Attribute.font(Font.systemFont(ofSize: 14, weight: UIFont.Weight.regular)),Attribute.paragraphStyle(style)])
        
        let alert = ST_BTAlertViewController.init(title: titleStr, message: content_string, imageName: "首页_icon_提示",cancelText:"稍后再说")
        
        alert.root_view_height = 290;
        
        alert.overCurrentContext = true;
        
        
        
        alert.confirm_closure = {
            
            
            guard let settingUrl =  URL(string: UIApplication.openSettingsURLString) else{
                return
            }
            
            UIApplication.shared.open(settingUrl, options: [:]) { (f) in
                
            }
            
        }
        
        GlobalPresent(toController: alert)
        
    }
    
    fileprivate func uploadImage(img:UIImage){
        
        guard let data = img.tian_uploadImageData()else{
            return
        }
        
        let key = img.tian_uploadFileKey()
        
        self.show_indeterminate_h_u_d()
        
        JVUpload(fileKey: key, data: data) { (f) in
            
        } success: { (json) in
            
            self.hidden_indeterminate_h_u_d()
            
            self.matchHandle(faceImgKey: key)
            
        } failure: { (code, err) in
            
            self.toast(text: err)
            
        }
        
        
    }
    
    fileprivate func matchHandle(faceImgKey:String){
        
        
        
        let loading = ST_MatchFaceLoadingController()
        
        loading.overCurrentContext = true
        
        GlobalPresent(toController: loading, animated: false)
        
        ST_BTGlobalDataCenter.shared.ai_detect_face_event()
        
        JVrequest(PH.faceMatchApi,parameters: ["match_url":faceImgKey] ,success: { (json) in
            
            loading.dismiss(animated: false) {
                
                if json["data"]["tip_code"].intValue == 2305{
                 
                    main_thread_execute {
                        
                        FACE_AVATAE_STATE = 4
                        
                        NotificationCenter.default.post(name: Notification.Name.approved_avatar, object: nil)
                        ST_ChangeAvatarManager.shared.hud_root_controller = self
                        ST_ChangeAvatarManager.shared.face_fail_match_options()
                    }
                    
                    return
                }
                FACE_AVATAE_STATE = 2
                
                if json["data"]["tip"].string != nil{
                    
                    let failure = ST_MatchFaceFailureController()
                    
                    failure.overCurrentContext = true
                    
                    GlobalPresent(toController: failure)
                    
                }else{
                    
                    FACE_AVATAE_STATE = 4
                    
                    MBProgressHUD.hide(for: self.view, animated: false)
                    
                    let hud = MBProgressHUD.showAdded(to: self.view, animated: true)
                    hud.mode = .text
                    hud.label.text = "比对中，稍后将结果通知你....."
                    hud.hide(animated: true, afterDelay: 3)
                    
                    main_thread_execute(afterDelay: 3) {
                        
                        self.goback_previous_controller()
                    }
                    
                }
            }
            
            
        }) { (code, err) in
            
            loading.dismiss(animated: false) {
                
                if code == 2305{
                    FACE_AVATAE_STATE = 4
                }
                
                ToastHud(text: err, view: ST_BTLaunchController.shared.view)
            }
        }
        
    }
    
    
    fileprivate func next_step_action(){
   
        
        #if !targetEnvironment(simulator)
        
        let vc = BDFaceLivenessViewController.init()
        let model = BDFaceLivingConfigModel.sharedInstance()
        let array = (model?.liveActionArray ?? []) as Array as [Any]
        vc.livenesswithList(array, order: model?.isByOrder ?? false, numberOfLiveness: model?.numOfLiveness ?? 3)
        vc.modalPresentationStyle = .fullScreen
        
        vc.backImage = {[weak self] image in
            
            guard let img = image else { return  }

            main_thread_execute {
                self?.uploadImage(img: img)
            }
            
        }
        
            let nav = UINavigationController.create_hiding_bar_navigation_controller(rootViewController: vc)
            
            GlobalPresent(toController: nav)
            
            #endif
    }
    
    
//    MARK: - config baidu
    fileprivate func baiduConfig(){
        
        #if !targetEnvironment(simulator)
        if !FaceSDKManager.sharedInstance().canWork() {
            print("授权失败，授权文件是否可用")
            return
        }
        
        // 初始化SDK配置参数，可使用默认配置
        // 设置最小检测人脸阈值
        FaceSDKManager.sharedInstance().setMinFaceSize(200)
        // 设置截取人脸图片宽
        FaceSDKManager.sharedInstance().setCropFaceSizeWidth(480)
        // 设置截取人脸图片高
        FaceSDKManager.sharedInstance().setCropFaceSizeHeight(640)
        // 设置人脸遮挡阀值
        FaceSDKManager.sharedInstance().setOccluThreshold(0.5)
        // 设置亮度阀值
        FaceSDKManager.sharedInstance().setMinIllumThreshold(40)
        FaceSDKManager.sharedInstance().setMaxIllumThreshold(240)
        // 设置图像模糊阀值
        FaceSDKManager.sharedInstance().setBlurThreshold(0.3)
        // 设置头部姿态角度
        FaceSDKManager.sharedInstance().setEulurAngleThrPitch(10, yaw: 10, roll: 10)
        // 设置人脸检测精度阀值
        FaceSDKManager.sharedInstance().setNotFaceThreshold(0.6)
        // 设置抠图的缩放倍数
        FaceSDKManager.sharedInstance().setCropEnlargeRatio(2.5)
        // 设置照片采集张数
        FaceSDKManager.sharedInstance().setMaxCropImageNum(1)
        // 设置超时时间
        FaceSDKManager.sharedInstance().conditionTimeout = 15
        // 设置开启口罩检测，非动作活体检测可以采集戴口罩图片
        FaceSDKManager.sharedInstance().setIsCheckMouthMask(true)
        // 设置开启口罩检测情况下，非动作活体检测口罩过滤阈值，默认0.8 不需要修改
        FaceSDKManager.sharedInstance().setMouthMaskThreshold(0.8)
        // 设置原始图缩放比例
        FaceSDKManager.sharedInstance().setImageWithScale(0.8)
        // 设置图片加密类型，type=0 基于base64 加密；type=1 基于百度安全算法加密
        FaceSDKManager.sharedInstance().setImageEncrypteWithType(0)
        // 初始化SDK功能函数
        FaceSDKManager.sharedInstance().initCollect()
        // 设置人脸过远框比例
        FaceSDKManager.sharedInstance().setMinRect(0.4)
   
        // 默认活体检测打开，顺序执行
        /*
         添加当前默认的动作，是否需要按照顺序，动作活体的数量（设置页面会根据这个numOfLiveness来判断选择了几个动作）
         */
        BDFaceLivingConfigModel.sharedInstance().liveActionArray.add(NSNumber.init(value: FaceLivenessActionType.liveEye.rawValue))
        BDFaceLivingConfigModel.sharedInstance().liveActionArray.add(NSNumber.init(value: FaceLivenessActionType.liveMouth.rawValue))
        BDFaceLivingConfigModel.sharedInstance().liveActionArray.add(NSNumber.init(value: FaceLivenessActionType.liveYawRight.rawValue))
        BDFaceLivingConfigModel.sharedInstance().liveActionArray.add(NSNumber.init(value: FaceLivenessActionType.liveYawLeft.rawValue))
        BDFaceLivingConfigModel.sharedInstance().liveActionArray.add(NSNumber.init(value: FaceLivenessActionType.livePitchUp.rawValue))
        BDFaceLivingConfigModel.sharedInstance().liveActionArray.add(NSNumber.init(value: FaceLivenessActionType.livePitchDown.rawValue))
//        BDFaceLivingConfigModel.sharedInstance().liveActionArray.add(NSNumber.init(value: FaceLivenessActionType.liveYaw.rawValue))
        BDFaceLivingConfigModel.sharedInstance().isByOrder = false
        BDFaceLivingConfigModel.sharedInstance().numOfLiveness = 3
        #endif
    }
    
//    MARK: - Properties
    fileprivate lazy var start_btn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.backgroundColor = UIColor.init(hexString: "#FEC207")
        control.cornerRadius = 22
        control.setTitleForAllStates("立即认证")
        control.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)
        control.setTitleColor(UIColor.white, for: UIControl.State.normal)
//        control.setTitleColor(UIColor.init(white: 1, alpha: 0.5), for: UIControl.State.disabled)
//        control.isEnabled = false
        control.addTarget(self, action: #selector(startHandle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    
    
    
    
    
    fileprivate lazy var faceTitleLabel:UILabel = {
        let control = UILabel.init()
        control.text = "认证后可获得以下权益"
        control.textColor = UIColor(hexString: "#333333")
        control.numberOfLines = 0
        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.semibold)
        return control
    }()
    
    fileprivate lazy var faceContentLabel:UILabel = {
        let control = UILabel.init()
        control.text = "认证用户能享受更多的交友资源与特权"
        control.textColor = UIColor(hexString: "#ACB4C0")
        control.numberOfLines = 0
        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)
        return control
    }()
    
    fileprivate lazy var lockImageView:UIImageView = {
        let control =  UIImageView.init(image: ST_ImageUtils.imageName("baidu_lock_icon"))
        return control
    }()
    
    
    fileprivate lazy var baiduBox:UIView = {
       let control =  UIView()
        control.borderColor = UIColor.init(hex: 0x42CEDA)
        control.borderWidth = 1
        control.cornerRadius = 2
        return control
    }()
    
    fileprivate lazy var baiduTitleLabel:UILabel = {
        let control = UILabel.init()
        control.text = "人脸认证资料由百度AI审核与保管"
        control.textColor = UIColor(hexString: "#42CEDA")
        control.numberOfLines = 0
        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)
        return control
    }()
    
    
    
    fileprivate lazy var baiduContentLabel:UILabel = {
        let control = UILabel.init()
        
        control.numberOfLines = 0
        
        let attrString = NSMutableAttributedString(string: "百度AI人脸识别采集图像信息后，将会根据采集的人脸信息与你的用户头像作比对。人脸信息将只作为真人头像对比认证使用，伴心无法查看用户的人脸信息，百度AI也绝对不会泄露用户信息，请放心认证。")
        let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14),.foregroundColor: UIColor(red: 0.67, green: 0.71, blue: 0.75, alpha: 1),.paragraphStyle:NSParagraphStyle.create_line_spacing_paragraph_style(lineSpacing: 3)]
        attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
        
        control.attributedText = attrString
        
        
        return control
    }()
    
    
    
    fileprivate lazy var sign_image_view:UIImageView = {
        let control = UIImageView.init(image: ST_ImageUtils.imageName("baidu_icon")!)
        return control
    }()
    
}
